package com.joy.core.config;

import com.zaxxer.hikari.HikariDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import javax.sql.DataSource;
import java.util.Objects;

@Configuration
public class DataSourceConfig {

    @Primary
    @Bean(name = "joyDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.hikari.joy")
    public HikariDataSource thorDataSource() {
        return new HikariDataSource();
    }

    @Bean(name = "joyQuartzDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.hikari.joy-quartz")
    public HikariDataSource crawlerDataSource() {
        return new HikariDataSource();
    }

    @Configuration
    @MapperScan(basePackages = {"com.joy.thor.mapper"}, sqlSessionFactoryRef = "joySqlSessionFactory")
    public static class ThorDataSourceConfig {
        @Primary
        @Bean(name = "joySqlSessionFactory")
        public SqlSessionFactory thorSqlSessionFactory(@Qualifier("joyDataSource") DataSource dataSource) throws Exception {
            SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
            sqlSessionFactoryBean.setDataSource(dataSource);
            Objects.requireNonNull(sqlSessionFactoryBean.getObject()).getConfiguration().setMapUnderscoreToCamelCase(true);
            return sqlSessionFactoryBean.getObject();
        }
    }
}
